#
# THIS IS MODULE DOWNLOADER.PY
#

import os, sys
from globvars import *

def download_build(buildno, prefdict, options):
    print "Could not find build, attempting to download..."

    os.chdir(prefdict['builddir'])

    # we delay the import of urllib, since we won't always end up here
    import urllib
    
    size = 100000

    if int(buildno) >= 2011:
        urlname = "ssl.opera.com:8037/builds/desktop/mac/10.50/"
        filename = "Opera_10.50_" + buildno + ".Unstripped.tar.gz"
    elif int(buildno) >= 8001:
        urlname = "ssl.opera.com:8037/builds/desktop/mac/10.50/"
        filename = "Opera_10.50_" + buildno + ".Unstripped.tar.gz"
    elif int(buildno) >= 6653:
        urlname ="ssl.opera.com:8037/builds/desktop/mac/10.10/"
        filename ="Opera_10.10_" + buildno + ".Unstripped.tar.gz"
    elif int(buildno) >= 6170:
        urlname = "ssl.opera.com:8037/builds/desktop/mac/10.00/"
        filename = "Opera_10.00_" + buildno + ".Unstripped.tar.gz"
    elif int(buildno) >= 6162:
        urlname = "ssl.opera.com:8037/builds/desktop/mac/10.00/"
        filename = "Opera_10.00_" + buildno + "_en.Unstripped.tar.gz"
    elif int(buildno) >= 6022:
        urlname = "ssl.opera.com:8037/builds/desktop/mac/10.00/"
        filename = "Opera_10.00_" + buildno + ".Unstripped.tar.gz"
    elif int(buildno) >= 5272:
        urlname = "ssl.opera.com:8037/builds/desktop/mac/9.65/"
        filename = "Opera_9.65_" + buildno + ".Unstripped.tar.gz"
    elif int(buildno) >= 5262:
        urlname = "ssl.opera.com:8037/builds/desktop/mac/9.64/"
        filename = "Opera_9.64_" + buildno + ".Unstripped.tar.gz"
    elif int(buildno) >= 5258:
        urlname = "ssl.opera.com:8037/builds/desktop/mac/9.63/"
        filename = "Opera_9.63_" + buildno + ".Unstripped.tar.gz"
    elif int(buildno) >= 5253:
        urlname = "ssl.opera.com:8037/builds/desktop/mac/9.62/"
        filename = "Opera_9.62_" + buildno + ".Unstripped.tar.gz"
    elif int(buildno) >= 5247:
        urlname = "ssl.opera.com:8037/builds/desktop/mac/9.61/"
        filename = "Opera_9.61_" + buildno + ".Unstripped.tar.gz"
    elif int(buildno) >= 5200:
        urlname = "ssl.opera.com:8037/builds/desktop/mac/9.60/"
        filename = "Opera_9.60_" + buildno + ".Unstripped.tar.gz"
    elif int(buildno) >= 4887:
        urlname = "ssl.opera.com:8037/builds/desktop/mac/9.52/"
        filename = "Opera_9.52_" + buildno + ".Unstripped.tar.gz"
    elif int(buildno) >= 4873:
        urlname = "ssl.opera.com:8037/builds/desktop/mac/9.51/"
        filename = "Opera_9.51_" + buildno + ".Unstripped.tar.gz"
    elif int(buildno) >= 4814:
        urlname = "ssl.opera.com:8037/builds/desktop/mac/9.50/"
        filename = "Opera_9.50_" + buildno + ".Unstripped.tar.gz"
    elif int(buildno) >= 4610:
        urlname = "ssl.opera.com:8037/builds/desktop/mac/9.50/"
        filename = "Opera.9.50." + buildno + ".all.Unstripped.tar.gz"
    else:
        urlname = "ssl.opera.com:8037/builds/desktop/mac/9.5/"
        filename = "Opera.9.5." + buildno + ".all.Unstripped.tar.gz"
        
    if options.verbose == True: print "Filename is: %s" % filename

    # construct some strings for use with urllib.urlopen and some
    # error messages
    https = "https://"

    # do some checking to construct our user/pass part of the url
    if prefdict.has_key('USER') and prefdict.has_key('PASS'):
        user_pass = prefdict['USER'] + ":" + prefdict['PASS'] + "@"
    elif prefdict.has_key('USER') and not prefdict.has_key('PASS'):
        user_pass = prefdict['USER'] + "@"
    else:
        user_pass = ""
        
        
    target = buildno + "/" + filename
    
    if options.verbose == True: print "URL is %s" % (https + urlname + target)
    # in this section I have no idea what to do, since urllib.urlopen acts retarded
    # when it doesn't find the file we ask for. one would think it would throw 
    # an exception, but no such luck.
    try:
        readfile = urllib.urlopen(https + user_pass + urlname + target)
    except IOError, info:
        print info
        sys.exit(1)
    try:    
        outfile = open(filename, "w")
    except:
        print "Couldn't create file %s" % filename
        print "Aborting..."
        sys.exit(1)
        
    readbytes = None
    totalsize = 0
    while (readbytes != ""):
        readbytes = readfile.read(size)
        totalsize += len(readbytes)
        if not (readbytes == ""):
            sys.stdout.write("\rGot %d KB (%d MB)" % ((totalsize/1000), 
                                                     (totalsize/(1000*1000))))
            sys.stdout.flush()
 
            outfile.write(readbytes)
    sys.stdout.write("\n")
    outfile.close()
    # this is a hack, because urllib.urlopen doesn't return anything if it 
    # doesn't find the file specified, it just reads the server error message page 
    # into its buffer and goes merrily on its way. 50000 is just a random number. 
    # usually when the download fails we get about 400 bytes of html when 
    # the server pops us a 404
    if totalsize < 50000:
        print "*" * 40
        print "Something is wrong, we didn't get more than %d bytes of data" % totalsize
        print "The most likely scenario is that build %s failed, leaving nothing but a log behind" % buildno
        print "Aborting, investigate this url:"
        print "%s" % (https + urlname + buildno + "/")
        os.unlink(filename)
        print "*" * 40
        sys.exit(1)

    if options.verbose == True:
        os.system("tar zxfv " + filename)
    else:
        os.system("tar zxf " + filename)

    os.system("mv Opera.app " + buildno + ".app")
    os.unlink(filename)
    operadir = buildno + ".app" + PRESET

    return operadir
